package com.dhl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhl.entity.SysMenu;
import com.dhl.entity.SysRole;
import com.dhl.entity.SysUser;
import com.dhl.mapper.SysMenuMapper;
import com.dhl.mapper.SysRoleMapper;
import com.dhl.service.SysRoleService;
import com.dhl.service.SysUserService;
import com.dhl.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2022-09-23 16:59:19
*/
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Override
    public SysUser getSysUserByUsername(String username) {
        return this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername,username));
    }

    @Override
    public String getUserAuthorityInfo(Long userId) {
        StringBuilder authority = new StringBuilder();
        // 获取所有的角色信息
        List<SysRole> roleList = sysRoleMapper.selectList(new LambdaQueryWrapper<SysRole>()
                .inSql(SysRole::getId,"select role_id from sys_user_role where user_id =" + userId)
        );
        if(roleList.size() > 0){
            String roleCodeStrs = roleList.stream().map(role -> "ROLE_"+role.getCode()).collect(Collectors.joining(","));
            authority.append(roleCodeStrs);
        }



        // 遍历所有角色，获取所有菜单权限，并且不重复
        Set<String> menuCodeSet = new HashSet<String>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                    .inSql(SysMenu::getId,"select menu_id from sys_role_menu where role_id =" + sysRole.getId())
            );
            for (SysMenu sysMenu : menuList) {
                // 获取权限编码可能为空
                String perms = sysMenu.getPerms();
                if(StringUtils.hasLength(perms)){
                    menuCodeSet.add(perms);
                }
            }
        }

        // 拼接
        if(menuCodeSet.size() > 0){
            authority.append(",");
            String menuCodeStrs = menuCodeSet.stream().collect(Collectors.joining(","));
            authority.append(menuCodeStrs);
        }
        return authority.toString();
    }
}




